package com.drought.rained.presenter;

import android.annotation.SuppressLint;

import com.drought.rained.BuildConfig;
import com.drought.rained.bean.DictionaryItemDataLJ;
import com.drought.rained.business.ParamsFactoryLJ;
import com.drought.rained.cache.UserInfoLJ;
import com.drought.rained.mvpview.DictionaryMvpViewLJ;
import com.drought.rained.response.DictionaryResponseLJ;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class DictionaryPresenterLJ extends BasePresenterLJ {
    private DictionaryMvpViewLJ mvpView;

    public DictionaryPresenterLJ(DictionaryMvpViewLJ mvpView) {
        this.mvpView = mvpView;

    }

    @SuppressLint("CheckResult")
    public void getDictionaryData(List<String> types) {
        List<Observable<DictionaryResponseLJ>> observableList = new ArrayList<>();
        for (String type : types) {
            Map<String, Object> formMap = new HashMap<>();
            formMap.put("dictType", type);
            observableList.add(req.getDictionaryData(BuildConfig.channel, UserInfoLJ.getToken(), ParamsFactoryLJ.getCommonParams(formMap)));
        }

        Observable.zip(observableList, new Function<Object[], ArrayList<ArrayList<DictionaryItemDataLJ>>>() {
            @Override
            public ArrayList<ArrayList<DictionaryItemDataLJ>> apply(Object[] objects) throws Exception {
                ArrayList<ArrayList<DictionaryItemDataLJ>> responseArr = new ArrayList<>();
                for (int i = 0; i < objects.length; i++) {
                    DictionaryResponseLJ response = (DictionaryResponseLJ) objects[i];
                    responseArr.add(response.getData());
                }
                return responseArr;
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())

                .subscribe(new Consumer<ArrayList<ArrayList<DictionaryItemDataLJ>>>() {

                    @Override
                    public void accept(ArrayList<ArrayList<DictionaryItemDataLJ>> arrayLists) throws Exception {
                        mvpView.onGetDataNext(arrayLists);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        mvpView.onGetDataError(throwable);
                    }
                });
    }
}
